package com.tanhua.dubbo.api;

import cn.hutool.core.util.PageUtil;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存
    public void save(Video video) {
        mongoTemplate.save(video);
    }

    //查询所有
    public List<Video> findAll(Integer page, Integer pagesize) {
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Video.class);
    }

    /**
     * 根据id查询推荐的视频数据
     *  1、如果redis数据足以分页，展示推荐的数据
     *  2、如果redis数据不足，查询所有
     */
    public List<Video> findByIds(String[] vids, Integer page, Integer pagesize) {
        //redis中支持的最大页数
        int totalPage = PageUtil.totalPage(vids.length, pagesize);//数据总数，每页查询条数 2
        if(page <= totalPage) {
            //根据id查询
            Criteria criteria = Criteria.where("id").in(vids);
            Query query = Query.query(criteria).skip((page - 1) * pagesize)
                    .limit(pagesize);
            return mongoTemplate.find(query,Video.class);
        }else{
            //查询所有，倒叙展示
            return findAll(page-totalPage,pagesize);
        }
    }

    //根据用户id，查询视频列表
    public PageResult findByUserId(Long uid, Integer page, Integer pagesize) {
        //1、创建Citeria对象
        Criteria criteria = Criteria.where("userId").is(uid);
        //2、创建Query
        Query query = Query.query(criteria);
        //3、查询总数
        long count = mongoTemplate.count(query, Video.class);
        //4、设置分页参数
        query.with(Sort.by(Sort.Order.desc("created")))
             .limit(pagesize)
             .skip((page - 1) * pagesize);
        //5、查询列表
        List<Video> list = mongoTemplate.find(query, Video.class);
        //6、返回
        return new PageResult(page,pagesize,count,list);
    }
}
